<template>
    <div>
        <el-card>
            <el-skeleton :rows="2" :loading="loading" animated>
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>Redis版本号</el-text>
                            <el-text type="primary">{{ redisInfo.redisVersion }}</el-text>
                        </el-space>
                    </el-col>
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>键值总数</el-text>
                            <el-text type="primary">{{ redisInfo.keyCount }}</el-text>
                        </el-space>
                    </el-col>
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>命中次数</el-text>
                            <el-text type="primary">{{ redisInfo.hitSuccessCount }}</el-text>
                        </el-space>
                    </el-col>
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>已用内存</el-text>
                            <el-text type="primary">{{ redisInfo.usedMemory }}</el-text>
                        </el-space>
                    </el-col>
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>内存峰值</el-text>
                            <el-text type="primary">{{ redisInfo.usedMemoryPeak }}</el-text>
                        </el-space>
                    </el-col>
                    <el-col :span="4">
                        <el-space direction="vertical">
                            <el-text>启动时间</el-text>
                            <el-text type="primary">{{ redisInfo.startTime }}</el-text>
                        </el-space>
                    </el-col>
                </el-row>
            </el-skeleton>
        </el-card>
        <el-card class="redisList">
            <div class="search-query">
                <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                    <el-form-item label="键" prop="key">
                        <el-input v-model="searchForm.key" placeholder="键" clearable />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleSearchReset(searchFormRef)">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>

            <el-table border :data="redisData" v-loading="loading" style="width: 100%;margin-top: 10px;"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />

                <el-table-column prop="key" label="键" />
                <!-- <el-table-column prop="value" label="值" /> -->
                <el-table-column fixed="right" label="操作">
                    <template v-slot="scope" #default>
                        <el-space wrap>
                            <el-button type="primary" @click="handleQuery(scope.row)" link>查询</el-button>
                            <el-button type="success" @click="handleViewTTL(scope.row)" link>修改TTL</el-button>
                            <el-button type="danger" @click="handleDelete(scope.row)" link>删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </div>
    <el-dialog v-model="visible" title="值" width="800px" :close-on-click-modal="false">
        
        
        <el-button @click="jsonFormat" type="primary">格式化</el-button>
        <el-button @click="jsonNoFormat" type="info">压缩</el-button>
        <div style="margin-top: 10px;" v-if="queryData.expire != -2">
            过期时间：<el-text type="success">{{ queryData.expire== -1?'永不过期':queryData.expire+'s'}}</el-text>
        </div>
         <v-ace-editor v-model:value="queryData.data" @init="jsonFormat" lang="json"
                      :readonly="aceConfig.readOnly" style="height:500px;margin-top: 20px;" class="ace-editor" />
                      
    </el-dialog>

    <el-dialog v-model="ttlVisible" title="更新TTL" width="800px" :close-on-click-modal="false">
        <el-form :model="ttlForm" label-position="top"  ref="ttlFormRef" >
            <el-form-item label="过期时间(s)" prop="ttl" required error="请输入过期时间">
                <el-input v-model="ttlForm.ttl" placeholder="请输入过期时间" clearable />
            </el-form-item>

        </el-form>
        <template #footer>
            <div>
                <el-button @click="ttlVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateTTL(ttlFormRef)">
                    保存
                </el-button>
            </div>
        </template>       
    </el-dialog>
</template>
<script setup lang="js">
import { ref, onMounted,reactive } from 'vue';
import redis from '@/services/redis';
import { VAceEditor } from 'vue3-ace-editor';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-chrome';
import 'ace-builds/src-noconflict/ext-language_tools';
import { ElMessage } from 'element-plus';

// import { JsonViewer } from "vue3-json-viewer";
// import "vue3-json-viewer/dist/index.css";

onMounted(() => {
    init()
    redisTable()
})

const redisData = ref()

const loading = ref(false)
const redisInfo = ref({})
const init = async () => {
    loading.value = true
    let res = await redis.getRedisIndex()

    if (res.code == 200) {
        redisInfo.value = res.data
        loading.value = false
    }

}

const redisTable = async () => {
    loading.value = true
    const res = await redis.listKeys({})
    if (res.code === 200) {
        redisData.value = res.data
        loading.value = false
    }
    
}

// const sseSource = new EventSource("/api/sse/connect");

// // 连接打开
// sseSource.onopen = function () {
//     console.log("连接打开");
// }

// // 连接错误
// sseSource.onerror = function (err) {
//     console.log("连接错误:", err);
// }

// // 接收到数据
// sseSource.onmessage = function (event) {
//     handleReceiveData(JSON.parse(event.data))
// }

// // 关闭链接
// const handleCloseSse = () => {
//     sseSource.close()
// }

// // 处理服务器返回的数据
// const handleReceiveData = (res) => {
//     redisInfo.value = res.data
// }

const searchFormRef = ref()
const searchForm = ref({
    key: ''
})

const handleSearch = async() => {
    const res = await redis.listKeys(searchForm.value)
    if(res.code === 200) {
        redisData.value = res.data
    }
}

const handleSearchReset = (formRef) => {
    formRef.resetFields()
}

// 复选框
let ids = []
const handleSelectionChange = (value) => {
    ids = []
    value.forEach(e => {
        ids.push(e.key)
    });
}

// 批量删除
const handleBatchDelete = async () => {
    if (ids.length == 0) {
        throw ElMessage({
            type: 'warning',
            message: "请选择"
        })
    }
    const res = await redis.deleteKey(ids)
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        redisTable()
    }
}

const visible = ref(false)
const queryData = ref({
    data: '',
    expire: '',
    key: ''
})
const handleQuery =  async (row) => {
    queryData.value.key = row.key
    const res = await redis.getValue({key:row.key})
    if(res.code === 200) {
        queryData.value.data = JSON.stringify(res.data.value)
        queryData.value.expire = res.data.expire
        visible.value = true
    }
}

//ace编辑器配置
const aceConfig = reactive({
    lang: 'json', //解析json
    readOnly: true, //是否只读
})

// JSON格式化
const jsonFormat = () => {
    try {
        queryData.value.data = JSON.stringify(JSON.parse(queryData.value.data),null,2)
    } catch (e) {
        console.log(e)
    }
};

// JSON压缩
const jsonNoFormat = () => {
    try {
        queryData.value.data = JSON.stringify(JSON.parse(queryData.value.data))
    } catch (e) {
        console.log(e)
    }
};

const ttlVisible = ref(false)
const ttlFormRef = ref()
const ttlForm = ref({
    key: '',
    ttl: ''
})

const handleViewTTL = (row) => {
    ttlForm.value.key = row.key
    ttlForm.value.ttl = ''
    ttlVisible.value = true
}

const handleUpdateTTL =  async(formRef) => {
    if (!formRef) return
    await formRef.validate((valid, fields) => {
        if (valid) {
            redis.updateTTL(ttlForm.value).then((res) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                }
            })
            ttlVisible.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 删除
const  handleDelete = async (row) => {
    const res = await redis.deleteKey([row.key])
    if(res.code === 200) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        redisTable()
    }
}
</script>

<style lang="less" scoped>
.redisList {
    margin-top: 20px;
}
</style>
